#coding:utf-8

from django.db import models

# Create your models here.


#环镜名称
class EnvironmentName(models.Model):
    # id
    name = models.CharField(max_length=256, db_index=True, verbose_name='环镜名称')
    desc = models.CharField(max_length=256, verbose_name='环镜描述')
    hosts = models.ManyToManyField('Host',blank=True, related_name='hosts_EnvironmentName', verbose_name='属于这个环镜的主机')

    def get_hosts(self):
        print ('models.py的输出……')
        print (self.id)
        print (self.desc)
        hosts_list = EnvironmentName.objects.get(id=self.id).hosts.all()
        print ('hosts_list is:',hosts_list)
        return hosts_list

    class Meta:
        verbose_name = '环镜名称'
        verbose_name_plural = verbose_name
        ordering = ['name', 'id']

    def __unicoding__(self):
        return self.name

    def __str__(self):
        return self.name


#主机列表
class Host(models.Model):
    # id
    hostname = models.CharField(max_length=256, db_index=True,verbose_name='主机名称')
    desc = models.CharField(max_length=256, verbose_name='主机描述')
    internetIP = models.GenericIPAddressField(protocol='ipv4', db_index=True,verbose_name='公网IP')
    intranetIP = models.GenericIPAddressField(protocol='ipv4', db_index=True,verbose_name='内网IP')
    runapps = models.ManyToManyField('Runapp',blank=True, verbose_name='运行的应用')

    def get_runapps(self):
        runapp_list = Host.objects.get(id=self.id).runapps.all()
        return runapp_list

    def get_env(self):
        env_list = Host.objects.get(id=self.id).hosts_EnvironmentName.all()
        print (env_list)
        return env_list

    class Meta:
        verbose_name = '主机'
        verbose_name_plural = verbose_name
        ordering = ['hostname', 'id']

    def __unicoding__(self):
        return self.hostname

    def __str__(self):
        return self.hostname


#主机上运行的应用列表
class Runapp(models.Model):
    # id
    appname = models.CharField(max_length=256, db_index=True, verbose_name='应用名称')
    ports = models.ManyToManyField('Appport', blank=True)

    def get_runapps(self):
        runapps_list = self.objects.all()
        return runapps_list

    def get_ports(self):
        port_list = Runapp.objects.get(id=self.id).ports.all()
        return port_list

    def get_host(self):
        hosts = Runapp.objects.get(id=self.id).host_set.all()
        return hosts

    class Meta:
        verbose_name = '应用名称'
        verbose_name_plural = verbose_name
        ordering = ['appname', 'id']

    def __unicoding__(self):
        return self.appname

    def __str__(self):
        return self.appname


#应用监听的端口列表
class Appport(models.Model):
    # id
    port = models.IntegerField(verbose_name='应用监听的端口')

    class Meta:
        verbose_name = '应用监听的端口'
        verbose_name_plural = verbose_name
        ordering = ['port', 'id']

    def __unicoding__(self):
        return self.port

    def __str__(self):  #不加此函数在RunappAdmin中，会显示Object，而不是数值
        return str(self.port)
